import type { ComponentInternalInstance } from "vue";
import type { ScrollViewOnScrollEvent } from '@uni-helper/uni-app-types';
import { debounce } from 'throttle-debounce';

export function getBoundingClientRect(currentInstance : ComponentInternalInstance | null, el : string) : Promise<UniApp.NodeInfo> {
	return new Promise((resovle) => {
		uni.createSelectorQuery().in(currentInstance).select(el).boundingClientRect((rect) => {
			resovle(rect as UniApp.NodeInfo);
		}).exec();
	});
}

export function getAllBoundingClientRect(currentInstance : ComponentInternalInstance | null, el : string) : Promise<UniApp.NodeInfo[]> {
	return new Promise(resolve => {
		uni.createSelectorQuery().in(currentInstance).selectAll(el).boundingClientRect((nodeInfos) => {
			resolve(nodeInfos as UniApp.NodeInfo[]);
		}).exec();
	})
}

export const scrollPosition = debounce(60, (event : ScrollViewOnScrollEvent, currentInstance : ComponentInternalInstance | null,
	el : string[], callback : (index : number, id : string, scrollTop : number) => void) => {
	const { scrollTop } = event.detail;
	if (scrollTop <= 40) {
		callback(0, '', scrollTop);
		return;
	};
	getAllBoundingClientRect(currentInstance, el[1]).then((nodeInfoList) => {
		let i = 0;
		let length = nodeInfoList.length;

		while (i < length) {
			const node = nodeInfoList[i];
			const heightTotal = nodeInfoList.slice(0, i + 1).reduce((heightTotal, info) => heightTotal + (info?.height || 0), 0);
			if (heightTotal - Math.abs(scrollTop) > 10) {
				callback(i, node.id as string, scrollTop);
				break;
			}
			i++;
		}
	})
});